package edu.po.au.server.service;

import javax.jdo.PersistenceManager;
import javax.persistence.EntityExistsException;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;

import edu.po.au.server.EPConstants;
import edu.po.au.server.PMF;
import edu.po.au.server.domain.Bid;
import edu.po.au.server.domain.User;

@Api(name = "au", version=EPConstants.API_VERSION, 
clientIds = {com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID, EPConstants.WEB_CLIENT_ID}, 
audiences = {EPConstants.ANDROID_AUDIENCE}, 
scopes={"https://www.googleapis.com/auth/userinfo.email"})
public class BidEndpoint {

	@ApiMethod(name = "bid.insert", path="bid/insert")
	public Bid insertUser(Bid bid) {
		PersistenceManager mgr = getPersistenceManager();
		
		try {
			if (containsBid(bid)) {
				throw new EntityExistsException("Object already exists");
			}
			mgr.makePersistent(bid);
		} finally {
			mgr.close();
		}
		return bid;
	}
	
	 
		private boolean containsBid(Bid bid) {
			PersistenceManager mgr = getPersistenceManager();
			boolean contains = true;
			try {
				mgr.getObjectById(User.class, bid.getBidId());
			} catch (javax.jdo.JDOObjectNotFoundException ex) {
				contains = false;
			} finally {
				mgr.close();
			}
			return contains;
		}

		private static PersistenceManager getPersistenceManager() {
			return PMF.get().getPersistenceManager();
		}

}
